import importlib
import traci
from dt import run, clean_temp_files
import argparse
from loguru import logger
import traceback

def load_config(terminal, env):
    # 生成配置文件名
    config_module_name = f"config.{terminal}_cfg"
    # 动态导入配置模块
    config_module = importlib.import_module(config_module_name)
    return config_module.SimulationConfig(region=terminal, env=env)

if __name__ == '__main__':
    terminal_choice = ['GuanDong','MingDong','PuDong','ShengDong','YiDong','ZhenDong','W4']
    env_choice = ['dev', 'prod', 'test', 'test2']

    parser = argparse.ArgumentParser()
    parser.add_argument('-tn', '--terminal', choices=terminal_choice, help='choose terminal')
    parser.add_argument('-env', '--env', choices=env_choice,  help='choose environment')

    args = parser.parse_args()
    terminal = args.terminal
    env = args.env

    if terminal is None:
        terminal = 'GuanDong'
    if env is None:
        env = 'dev'

    clean_temp_files() #在项目启动前清理临时文件
    configs = load_config(terminal, env)
    while True:
        try:
            if traci.isLoaded():
                traci.close()
            run(configs)
        except Exception as e:
            logger.info(f"启动仿真时发生错误: {e}")
            # logger.info(traceback.format_exc())
